package com.peanut.baby.mvp.expert.qa;

import android.app.Activity;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.QA;

import java.util.List;

import cn.nekocode.rxlifecycle.RxLifecycle;
import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/8/10.
 */

public class ExpertQaPresenter implements ExpertQaContract.Presenter{
    ExpertQaContract.View view;
    private Activity activity;
    public ExpertQaPresenter(ExpertQaContract.View view,Activity activity) {
        this.view = view;
        this.activity = activity;
    }

    @Override
    public void getQAList(String userId,int pageNo, int pageSize) {
        String token = InitManager.getInstance().getUser() == null? "":InitManager.getInstance().getUser().userToken;
        Observable observable = RetrofitClient.getInstance().getExpertQaList(userId,token,pageNo,pageSize);
        observable.compose(BaseScheduler.<BaseResponse<List<QA>>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<List<QA>>() {
            @Override
            protected void onHandleSuccess(List<QA> qas) {
                view.onGetQAListSuccess(qas);
            }

            @Override
            protected void onHandleError(String code,String error) {
                view.onRequestFailed(error);
            }
        });
    }

    @Override
    public void praiseQA(final QA qa) {
        Observable obs = RetrofitClient.getInstance().praiseQA(qa.id+"", InitManager.getInstance().getUserId(),InitManager.getInstance().getUser().userToken);
        obs.compose(BaseScheduler.<BaseResponse<QA>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<QA>() {
            @Override
            protected void onHandleSuccess(QA o) {
                qa.praiseFlag = o.praiseFlag;
                qa.praiseCount = o.praiseCount;
                view.onPraiseSuccess(o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onPraiseFailed("请求失败 "+msg);
            }

        });
    }
}
